<template>
  <div class="sms">
    <div class="back">
      <el-page-header
        v-if="state == 2"
        title="上一步"
        @back="
          () => {
            state = 1
            entity.code = ''
          }
        "
      />
    </div>

    <h2>邮箱验证码</h2>
    <el-form ref="dataForm" :rules="formRules" :model="entity" @submit.prevent>
      <div v-if="state == 1">
        <el-form-item prop="email">
          <j-input-wrapper>
            <el-input
              ref="emailInput"
              v-model="entity.email"
              @keyup.enter="showCaptchaHandler"
              placeholder="请输入邮箱地址"
              clearable
            />
          </j-input-wrapper>
        </el-form-item>

        <br />
        <el-button
          type="primary"
          :disabled="sms.seconds > 0"
          :loading="sms.loading"
          @click="showCaptchaHandler"
          >发送验证码
          {{ sms.seconds > 0 ? '（' + sms.seconds + '）' : '' }}</el-button
        >
        >
      </div>

      <div v-else>
        <p>
          已向邮箱&nbsp;<span>{{ entity.email }}</span>
        </p>
        <p>发送验证码，请填写</p>
        <br />

        <el-form-item prop="code">
          <j-input-wrapper>
            <el-input
              ref="passwordInput"
              v-model="entity.code"
              :disabled="loading"
              placeholder="请输入验证码"
              clearable
            />
          </j-input-wrapper>
        </el-form-item>
        <el-button
          type="primary"
          :disabled="sms.seconds > 0"
          :loading="sms.loading"
          @click="showCaptchaHandler"
        >
          重新发送 {{ sms.seconds > 0 ? '（' + sms.seconds + '）' : '' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import {
  // sendEmailSms,
  smsLogin,
} from '@/api/login'

function sendEmailSms() {
  return new Promise((resolve) => {
    resolve({
      data: {
        code: 200,
        message: '发送成功',
      },
    })
  })
}

export default {
  name: 'Sms',
  emits: ['captcha', 'login-success'],
  data() {
    return {
      entity: {
        email: '',
        code: '',
        smsType: 'login',
      },
      formRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
        ],
      },
      state: 1,
      loading: false,
      sms: {
        loading: false,
        seconds: 0,
        interval: null,
      },
    }
  },
  watch: {
    'entity.code'() {
      if (this.entity.code && this.entity.code.length == 6) {
        this.smsLoginHandler()
      }
    },
  },
  beforeUnmount() {
    if (this.sms.interval) clearInterval(this.interval)
  },
  methods: {
    showCaptchaHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$emit('captcha', this.verifySuccessHandler)
        }
      })
    },
    verifySuccessHandler(captchaVerification) {
      this.sms.loading = true

      let data = Object.assign(this.entity, captchaVerification)
      sendEmailSms(data)
        .then((res) => {
          this.entity.ticket = res.data.data
          this.$message.success('发送成功')

          this.state = 2
          this.sms.seconds = 60
          this.$nextTick(() => {
            this.$refs.passwordInput.$el.children[0].focus()
          })

          this.sms.interval = setInterval(() => {
            if (this.sms.seconds == 0) {
              clearInterval(this.sms.interval)
              this.sms.interval = null
            } else {
              this.sms.seconds--
            }
          }, 1000)
        })
        .finally(() => {
          this.sms.loading = false
        })
    },
    smsLoginHandler() {
      this.loading = true
      smsLogin(this.entity)
        .then((res) => {
          this.$message.success('登录成功')
          this.$emit('login-success', res)
        })
        .catch(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style lang="scss">
.sms {
  position: relative;
  height: 100%;

  .back {
    position: absolute;
    top: 1rem;
    left: -2rem;
  }

  .van-password-input {
    width: 100%;
    margin: 0;
  }

  p {
    text-align: center;
    margin-bottom: 1rem;

    span {
      color: var(--el-color-primary);
    }
  }
}
</style>
